<template>
  <div class="map-view">
    <div class="total-view">
        <div class="item">
          <div>地块数</div>
          <div class="num">{{farmTotal?.farmLandCount}}</div>
        </div>
        <div class="item">
          <div>地块面积(亩)</div>
          <div class="num">{{farmTotal?.farmLandTotal}}</div>
        </div>
    </div>
    <MapView ref="landMap" 
        @init="initMap" 
        @onClick="onClickLand"
        :params="querySreach"
        @complete="getLandList"
        :location="locationObj"  />
    <div class="location-view" @click="btnLocation">
      <Icon name="aim" class="icon-location"  color="#07c160" />
    </div>
    <div class="right-bottom-view">
         <Button plain
            type="success" 
            :key="item.value"
            v-for="(item,index) in btnList" 
            @click="btnOpen(item)" 
            :style="{display:index==2 && getTextName(formdata[item.key],item.key)?.length>4?'flex':'block'}"
            class="btn-top">
            
            {{formdata[item.key]?getTextName(formdata[item.key],item.key):item.text}}
          </Button>
    </div>
    <Popup v-model:show="showPicker"  :position="popType==1?'top':'bottom'">
        <SearchPanel v-if="popType==1" @onClick="onSearch" @onCancel="showPicker=false" />
        <Picker v-else
          v-model="selectedValues"
          :columns="columns"
          :title="title" 
          :columns-field-names="{text:'meaning',value:'code'}"
          @cancel="showPicker = false"
          @confirm="onConfirm"
        />
    </Popup>
     <Popup
        v-model:show="openPopup"
        :overlay="true"
        position="bottom"
        :overlay-style="{backgroundColor:'#00000010'}"
        :style="{ padding:'10px 0' }">
          <!-- 地块详情 -->
         <landInfo v-if="openPopup" ref="landInfoRef" :farmLandId="farmLandId" @onClick="openEidt"></landInfo>
      </Popup>
      <Popup
        v-model:show="openEidtPopup"
        :overlay="true"
        close-icon="close"
        closeable
        position="bottom"
        :overlay-style="{backgroundColor:'#00000010'}"
        :style="{ padding:'10px 0', height: '100%' }">
        <template v-if="openEidtPopup">
            <!-- 地块分组编辑 -->
          <landGroup v-if="openEidtType==1" :farmLandId="farmLandId" @onSuccess="closeEidt"></landGroup>
          <!-- 地块标签编辑 -->
          <landTags v-if="openEidtType==2" :farmLandId="farmLandId" @onSuccess="closeEidt"></landTags>
            <!-- 地块权属编辑 -->
          <landBelong v-if="openEidtType==3" :farmLandId="farmLandId" @onSuccess="closeEidt"></landBelong>
        </template>
      </Popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import {
  getCommonSelect,
  getFarmLandCount,
  getLandTypeList,
  getLandTagsList} from '@/api/gis'
import MapView from './components/home-land.vue'
import SearchPanel from './components/SearchPanel.vue'
import landInfo from './components/landInfo.vue'
import landGroup from './components/landGroup.vue'
import landBelong from './components/landBelong.vue'
import landTags from './components/landTags.vue'
import { getCookie } from '@/utils/httpParamsHandler';
import { Button,Popup,Picker,Icon} from 'vant';
const showPicker:any = ref(false)
const openPopup:any = ref(false)
const openEidtPopup:any = ref(false)
const openEidtType:any = ref(1)
const title:any = ref('')
const formdata:any =reactive({})
const formdataKey:any =ref('')
const farmLandId:any =ref('')
const popType:any = ref(1)
const landMap:any =ref(null)
const btnList:any =ref([
  {text:'搜索位置',value:1,key:'key1',icon:'location-o'},
  {text:'地块分组',value:2,key:'landGroupId',icon:'envelop-o'},
  {text:'作物品种',value:3,key:'cropId',icon:'flower-o'},
  {text:'地块类型',value:4,key:'landTypeId',icon:'star-o'},
  {text:'地块标签',value:5,key:'landTagId',icon:'flag-o'}
]) 
const landGroupList:any =ref([])
const cropList:any =ref([])
const landTypeList:any =ref([])
const tagsTypeList:any =ref([])
const columns:any = ref([])
const landInfoRef:any = ref(null)
const selectedValues:any = ref([])
const landMapList:any = ref([])
const farmTotal:any = ref({farmLandCount:0,farmLandTotal:0}) 
const locationObj = ref({})
const querySreach = ref({})
let mapView:any= null

onMounted(async ()=>{
  getSelectList()
  getLandTotal()
})

const getLandTotal =async ()=>{
 let res:any = await getFarmLandCount({
  ...formdata,
  farmId:getCookie('farmId'),
  landTagId:formdata?.landTagId?[formdata?.landTagId]:[],
  purPlantingPlanId:formdata?.cropId||null,
  cropId:null
 })
 if(res.success){
  farmTotal.value = res.data ||{}
 }
}

const getSelectList =async()=>{
  //分组
  let res:any = await getCommonSelect({page:1,limit:100,param1:getCookie('farmId'),lovCode:'TANC_LAND_GROUP'})
  if(res.success){
    landGroupList.value = res.data||[]
  }
//作物-查询执行中
let res1:any = await getCommonSelect({page:1,limit:100,param1:getCookie('farmId'),lovCode:'TANC_PLANTING_PLAN_2'})
  if(res1.success){
    cropList.value = res1.data||[]
  }
  //类型
  let res2:any = await getLandTypeList({page:1,limit:100,companyId:getCookie('companyId')})
  if(res2.success){
    landTypeList.value = res2.data.map((item:any)=>{
      return {
        meaning:item.landTypeName,
        code:item.landTypeId
      }
    })
  }

  //标签
  let res3:any = await getLandTagsList({page:1,limit:100,companyId:getCookie('companyId')})
  if(res3.success){
    tagsTypeList.value = res3.data.map((item:any)=>{
      return {
        meaning:item.tagName,
        code:item.landTagId
      }
    })
  }
}

const initMap =(view:any)=>{
  mapView=view
}

const getLandList =(data:any)=>{
  let list = data ||[]
  landMapList.value = list
  let centerList =[]
  list.forEach((item:any)=>{
     centerList.push([Number(item.locationLongitude),Number(item.locationLatitude)])
  })
  landMap.value.goCenterList(centerList)
}

const flattenArrayList =(arr:any)=> {
  return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArrayList(val)) : acc.concat(val), []);
}

const onClickLand =(row:any)=>{
  farmLandId.value = row.farmLandId
  openPopup.value = true
}

const openEidt =(openType:any)=>{
  openEidtType.value = openType
  openEidtPopup.value = true
}
const closeEidt =()=>{
  openEidtPopup.value = false
  landInfoRef.value.getLandInfo()
}

const btnOpen =(item:any)=>{
  showPicker.value= true
  title.value= item.text
  formdataKey.value=item.key
  popType.value = item.value
  selectedValues.value =[formdata[item.key]]||['']
  let objlist ={ meaning: '全部', code: '' }
  if(item.value==2){
    columns.value =[objlist,...landGroupList.value] 
  }else if(item.value==3){
    columns.value =[objlist,...cropList.value] 
  }else if(item.value==4){
    columns.value =[objlist,...landTypeList.value] 
  }else if(item.value==5){
    columns.value =[objlist,...tagsTypeList.value] 
  }
}
const getTextName =(Id:any,key:any)=>{
  if(key=='landGroupId'){
   return landGroupList.value.find((row:any)=>row.code==Id)?.meaning
  }
  if(key=='cropId'){
   return cropList.value.find((row:any)=>row.code==Id)?.meaning
  }
  if(key=='landTypeId'){
   return landTypeList.value.find((row:any)=>row.code==Id)?.meaning
  }
  if(key=='landTagId'){
   return tagsTypeList.value.find((row:any)=>row.code==Id)?.meaning
  }
  return ''
}



const onConfirm = async(item:any)=>{
  showPicker.value= false
  formdata[formdataKey.value]=item.selectedValues[0]
  let params={
      landGroupId:formdata.landGroupId,
      landTypeId:formdata.landTypeId,
      farmLandName:formdata?.farmLandName,
      landTagId:formdata?.landTagId,
      plantingPlanId:formdata?.cropId
   }
  querySreach.value = params
  getLandTotal()
  filterList(params)
}

const filterList = (params:any)=>{
  let filterList =landMapList.value.filter((item:any)=>{
   return (item.landGroupId == params?.landGroupId ||!params?.landGroupId) &&
        (item.landTypeId == params?.landTypeId ||!params?.landTypeId) &&
        (item.tagsId?.indexOf(params?.landTagId)>=0||!params?.landTagId) &&
        (item.cropId == params?.cropId ||!params?.cropId) &&
        (item.farmLandName?.indexOf(params?.farmLandName)>=0||!params.farmLandName)
    })

  let centerList =[]
    filterList.forEach((item:any)=>{
     centerList.push([Number(item.locationLongitude),Number(item.locationLatitude)])
  })
  landMap.value.goCenterList(centerList)
}

//定位当前
const btnLocation =()=>{
        wx.getLocation({
        type: 'wgs84',
        success: (res:any)=> {
          locationObj.value = {
            longitude:Number(res.longitude),
            latitude:Number(res.latitude)
          }
        },
        fail: (err:any)=> {
        }
   });
}
const onSearch =(row:any)=>{
   showPicker.value = false
   let item= {longitude:row.longitude,latitude:row.latitude}
   landMap.value.goCenterMartk(item)
   
}
</script>
<style lang="scss" scoped>
.map-view{
  height:100vh;
  width:100vw;
  position: relative;
  overflow: hidden;
}
.right-bottom-view .van-button{
  --van-button-normal-font-size:12px;
  --van-button-normal-padding:2px 4px;
  --van-button-default-height: 30px;
  --van-button-default-line-height:30px;
}
.total-view{
  display: flex;
  z-index: 999;
  position: absolute;
  top:10px;
  width:300px;
  left:50%;
  margin-left:-150px;
  align-items: center;
  justify-content: space-between;
  .item{
    color:#fff;
    font-size:13px;
    background-color: #00000090;
    border-radius:4px;
    width:120px;
    text-align: center;
    padding:5px 0;
    .num{
      font-size:15px;
      font-weight: bold;
    }
  }
}
.right-bottom-view{
  z-index: 999;
  position: absolute;
  bottom:20px;
  right: 10px;
  width:70px;
  text-align: right;
  .btn-top{
    margin-top:6px;
    width:70px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.location-view{
  position: absolute;
  z-index:99;
  left:10px;
  bottom:100px;
  height:40px;
  width:40px;
  background-color: #fff;
  border-radius:4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size:15px;
  .icon-location::before{
    font-size:24px;
  }
}

</style>
